package com.example.newsapp.data.database.databaseModel;

import android.content.Context
import androidx.room.Room
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.newsapp.data.database.NewsDatabase

// 数据库迁移策略
val MIGRATION_2_3: Migration = object : Migration(2, 3) {
    override fun migrate(database: SupportSQLiteDatabase) {
        // 创建一个新表，使用新的结构
        database.execSQL(
            """
            CREATE TABLE news_items_new (
                id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                title TEXT NOT NULL,
                source TEXT NOT NULL,
                picture TEXT NOT NULL,
                text TEXT NOT NULL,
                num INTEGER NOT NULL,
                type TEXT NOT NULL
            )
        """.trimIndent()
        )

        // 将旧表中的数据迁移到新表
        database.execSQL(
            "INSERT INTO news_items_new (id, title, source, picture, text, num, type) " +
                    "SELECT id, title, source, CAST(picture AS TEXT), text, num, type FROM news_items"
        )

        // 删除旧表
        database.execSQL("DROP TABLE news_items")

        // 将新表重命名为旧表的名称
        database.execSQL("ALTER TABLE news_items_new RENAME TO news_items")
    }
}
// 数据库操作类
class NewsDatabaseModel(private val context: Context) {
    private val newsDatabase by lazy {
        Room.databaseBuilder(
            context = context,
            klass = NewsDatabase::class.java,
            name = "app_database"
        )
            .addMigrations(MIGRATION_2_3)
            .build()
    }

    // 数据操作语句
    val dateSelect = newsDatabase.newsDao()

    // 自定义语句
    var supportDb = newsDatabase.openHelper.writableDatabase



}
